package server

import (
	"CheRpc/encode"
	"CheRpc/regist"
	"encoding/json"
	"fmt"
	"net"
	"strings"
	"sync"
)

var g regist.GloabRegist = regist.GloabRegist{}

type Servers struct {
	LockS sync.Locker
}

func (ser *Servers) StartServer(add string) {
	ser.LockS = &sync.Mutex{}
	cli, err := net.Listen("tcp", add)
	if err != nil {
		panic(err)
	}
	fmt.Println("Server start...")
	g.Init()
	for {
		go ser.dispCon(cli.Accept())
	}

}
func (ser *Servers) dispCon(conn net.Conn, err error) {
	if err != nil {
		fmt.Print(err)
		return
	}
	for {
		respByte := make([]byte, 512)
		conn.Read(respByte)

		ser.HandleResponse(conn, respByte)
	}

}

var SendQuque map[net.Conn]net.Conn = make(map[net.Conn]net.Conn)

func (ser *Servers) SendResponse(con net.Conn, meg []byte) {
	con.Write(meg)
}

func (ser *Servers) CallMethod(Cli net.Conn, con regist.ServerItem, body []byte) {
	//fmt.Println(string(body))

	con.Con.Write(body)
	ser.LockS.Lock()
	SendQuque[con.Con] = Cli
	ser.LockS.Unlock()
}
func (ser *Servers) HandleResponse(con net.Conn, req []byte) error {
	msg := encode.RequestMeg{}
	un := encode.Untily{}
	ReqLen := un.BytesToInt(req[:4])
	msg.ReqId = un.BytesToInt(req[4:8])
	if ReqLen == 0 {
		return nil
	}
	Body := req[8 : ReqLen+8]
	switch msg.ReqId {
	case 0:
		obj := encode.CallBody{}
		json.Unmarshal(Body, &obj)
		se := g.GetSer(strings.Split(obj.Method, ".")[0])
		ser.CallMethod(con, se, req)
	case 1:
		//表示为注册
		obj := encode.ResistBody{}
		json.Unmarshal(Body, &obj)
		fmt.Println("服务注册成功")
		g.Regist(obj.ServerName, regist.ServerItem{Con: con, StartTime: obj.StartTime, Add: obj.Add, TimeOut: obj.TimeOut})
		ser.SendResponse(con, []byte("服务注册成功"))
	case 2:
		//var alls map[string]regist.ServerItem
		res, _ := json.Marshal(g.GetAll())
		ser.SendResponse(con, []byte(res))
	case 4:
		if v, k := SendQuque[con]; k {

			v.Write(req)
		}
	}
	return nil
}
